<template>
  <div class="flex flex-col h-full">
    <a-card>
      <div class="flex justify-between items-center">
        <a-button type="primary" class="mr-4" @click="router.go(-1)"> 返回 </a-button>
        <a-descriptions class="mt-3" :column="4">
          <a-descriptions-item label="单号"> {{ formState?.thdh || '-' }}</a-descriptions-item>
          <a-descriptions-item label="日期">{{ formState?.thsj || '-' }}</a-descriptions-item>
          <a-descriptions-item label="退货仓库"> {{ formState?.thckmc || '-' }}</a-descriptions-item>
          <a-descriptions-item label="供应商">{{ formState?.gysmc || '-' }}</a-descriptions-item>
          <a-descriptions-item label="发票状态">{{ formState?.fpzt === 0 ? '普通' : '在途' }}</a-descriptions-item>
          <a-descriptions-item label="发票号">{{ formState?.fph || '-' }}</a-descriptions-item>
          <a-descriptions-item label="制单人">{{ formState?.createUser || '-' }}</a-descriptions-item>
          <a-descriptions-item label="制单时间">{{ formState?.createTime || '-' }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </a-card>
    <a-card class="mt-2 flex-1 h-full" :body-style="{ display: 'flex', width: '100%', height: '100%', overflow: 'hidden' }">
      <BaseTable
        :data-source="dataSource"
        column-code="00001086"
        class="overflow-auto flex-1"
        :scroll="{ x: 2200 }"
        :loading="loading"
        max-fill
        :extra-height="64"
        :custom-row="(record) => ({ onClick: () => record.lsh && onSelectRow(record) })"
        :exclude-columns="['zsm']"
        :row-class-name="getRowClass"
      >
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex === 'NO'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'status'">
            <a-tag v-if="record.status === 0" color="blue">未确认</a-tag>
            <a-tag v-if="record.status === 1" color="green">已确认</a-tag>
          </template>
          <template v-if="column.dataIndex === 'ypmc'">
            <MedicineInfo :value="{ mc: record?.ypmc, gg: record?.gg, cj: record?.cj }" />
          </template>
          <template v-if="column.dataIndex === 'thsl'">
            <EditCell title="退货数量">
              <BaseInput
                v-model:value="record.thsl"
                class="text-right"
                :auto-focus="focusCell === record.key"
                placeholder="请输入"
                @change="onChanegSl(record)"
                @blur="!record.isNew && fetchSave(record)"
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'thdj'">
            <EditCell title="退货单价">
              <a-input
                v-model:value="record.thdj"
                v-input-blur:float.5
                v-input:float.5
                class="text-right"
                placeholder="请输入"
                @blur="!record.isNew && fetchSave(record)"
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'thyy'">
            <EditCell title="退货缘由">
              <a-input v-model:value="record.thyy" placeholder="请输入" @blur="!record.isNew && fetchSave(record)" />
            </EditCell>
          </template>
          <!-- 追溯码 -->
          <template v-if="column.dataIndex === 'zsm'">
            <span :class="record.kcTraceCodeRecordList?.length !== record.thsl ? 'text-red-500' : ''">
              {{ record.kcTraceCodeRecordList?.length || 0 }}/{{ record.thsl }}
            </span>
          </template>
          <template v-if="column.dataIndex === 'cmemo'">
            <EditCell title="备注">
              <a-input v-model:value="record.cmemo" placeholder="请输入" @blur="!record.isNew && fetchSave(record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <BaseButton confirm-text="确认删除？" type="text" danger size="small" @click="onDelete(record)">删除</BaseButton>
          </template>
        </template>
        <template #footer>
          <div class="text-center sticky bottom-0">
            <a-button class="mr-2" type="primary" ghost @click="open = true"> 新增一行 </a-button>
            <a-button type="primary" :disabled="dataSource.length === 0" @click="saveNewRows()"> 保存 </a-button>
          </div>
        </template>
      </BaseTable>
    </a-card>
    <SelectDetail v-model:open="open" :thckbh="formState.thckbh" :gysbh="formState.gysbh" :data-source="dataSource" @ok="addDetail" />
  </div>
</template>

<script setup>
import { ref, watchEffect } from 'vue'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import BaseButton from '@/components/BaseButton'
import BaseTable from '@/components/BaseTable'
import { post } from '@/utils/request'
import EditCell from '@/components/EditCell'
import SelectDetail from './SelectDetail'

const formState = ref({})
const open = ref(false)
const loading = ref(false)
const currentRow = ref({})
const dataSource = ref([])
const route = useRoute()
const focusCell = ref('')
const router = useRouter()
const fetchSave = async (row, isRefresh = true) => {
  if (!row.thdj) return message.error('退货单价不能为空')
  if (!row.thsl) return message.error('退货数量不能为空')
  row.thdh = formState.value.thdh
  const { code, msg } = await post('/drugStorage/psiform/doSavereturnOrderDetail', row)
  if (code !== 0) return message.error(msg || '操作失败')
  message.destroy()
  message.success(row.isNew ? '新增成功' : '修改成功')
  isRefresh && getDetailData()
}
const onChanegSl = (e) => {
  if (!e.thsl) return
  if (!e.thdj) return
  e.thje = parseFloat(e.thsl * e.thdj).toFixed(2)
}
const getRowClass = (record) => {
  return {
    'table-row-new': record.isNew,
    'table-row-selected': record.ph === currentRow.value.ph
  }
}
const saveNewRows = async () => {
  const newRow = dataSource.value.filter((item) => item.isNew)
  newRow.forEach((item, index) => {
    if (item.ypbh && item.sl) {
      fetchSave(item, index === newRow.length - 1)
    } else {
      message.destroy()
      message.error('请填写完整信息')
    }
  })
}

//添加行
const addDetail = (rows) => {
  const addRows = rows.map((row) => {
    row.isNew = true
    row.rklsh = row.lsh
    row.ysrkdj = row.dj.toFixed(5)
    row.ysrkje = row.je.toFixed(2)
    row.ysrksl = row.sl
    row.dskc
    row.lsh = ''
    row.thsl = 1
    row.thdj = row.dj.toFixed(5)
    row.thje = row.dj.toFixed(5)
    row.key = 'new' + Math.random()
    return row
  })
  dataSource.value = dataSource.value.concat(addRows)
  setTimeout(() => {
    focusCell.value = addRows[0].key
  }, 600)
}

const getMainData = async () => {
  const { data, code } = await post('/drugStorage/psiform/getReturnOrderList', {
    mcbm: route.query?.thdh
  })
  if (code === 0) {
    formState.value = data[0]
  }
}
const getDetailData = async () => {
  loading.value = true
  const { data, code } = await post('/drugStorage/psiform/getreturnOrderDetailList', {
    thdh: route.query?.thdh
  })
  loading.value = false
  if (code === 0) {
    dataSource.value = data.map((item) => {
      item.key = item.lsh
      item.thdj = item?.thdj.toFixed(5)
      item.thje = item?.thje.toFixed(2)
      item.ysrkdj = item?.ysrkdj.toFixed(5)
      item.ysrkje = item?.ysrkje.toFixed(2)

      return item
    })
    if (dataSource.value.length > 0) {
      if (currentRow.value.lsh) {
        currentRow.value = dataSource.value.find((item) => item.lsh === currentRow.value.lsh)
      } else {
        currentRow.value = dataSource.value[0]
      }
    }
  }
}
const onSelectRow = (row) => {
  currentRow.value = row
}

const onDelete = async (row) => {
  if (row.isNew) {
    dataSource.value = dataSource.value.filter((item) => item.key !== row.key)
  } else {
    const { code, msg } = await post('/drugStorage/psiform/doDeletereturnOrderDetail', {
      dh: route.query?.thdh,
      lsh: row.lsh
    })
    if (code !== 0) return message.error(msg || '操作失败')
    getDetailData()
    message.success('删除成功')
  }
}

watchEffect(() => {
  if (route && route.query?.thdh) {
    getMainData()
    getDetailData()
  }
})
</script>
<style lang="less" scoped>
:deep(.ant-card-head) {
  padding-left: 8px;
}
</style>
